package com.zj.core.tools

import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import com.dialogutils.ToastUtil
import com.log.Logger
import com.systemutils.PermissionHelper
import com.zj.core.base.BaseApplication
import com.zj.core.interfaces.ActivityLifecycleIml
import com.zj.core.interfaces.annotations.Permissions
import kotlinx.coroutines.*
import org.aspectj.lang.JoinPoint
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.After
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.reflect.MethodSignature

@Aspect
class AspectTools {
    private var mActivityList:ArrayList<Activity>?=ArrayList()
    private var mJoinPoint: ProceedingJoinPoint? = null
    private var LAST_HANDLE_TIME: Long = 0        //上次操作时间
    private var REQ_CODE_PERMISSION = 1         //请求权限

    init {
        globleListener()
    }

    /**
     * 使用Aspectx进行埋点
     * 监听所有方法
     */
    @After("execution(* *..*Activity.*(..))|| execution(* *..*Dialog.*(..))")
    fun greeterAdvice(joinPoint: JoinPoint) {
        LAST_HANDLE_TIME = System.currentTimeMillis()
    }

    /**
     * 检查权限
     */
    @Around("@annotation(com.zj.core.interfaces.annotations.Permissions)")
    fun checkPermission(joinPoint: ProceedingJoinPoint){
        mJoinPoint = joinPoint
        val permissionValue = (joinPoint.signature as MethodSignature).method.getAnnotation(Permissions::class.java)

        mActivityList?.let {
            PermissionHelper.getInstance().requestPermissions(
                it[it.size-1], { _, list, _ ->
                    if (list?.size != 0) {
                        ActivityCompat.requestPermissions(it[it.size-1], list!!, PermissionHelper.REQUEST_CODE)
                    } else {
                        joinPoint.proceed()
                    }
                }, permissionValue.value, REQ_CODE_PERMISSION
            )
        }
    }

    /**
     * 等待权限结果
     */
    @After("execution(* android.app.Activity.onRequestPermissionsResult(..))")
    fun waitPermissionResult(point: JoinPoint) {
        val params = point.args
        if (params[0] == PermissionHelper.REQUEST_CODE) {
            val intArr = params[2] as IntArray
            with(intArr) {
                for (num in 0 until this.size) {
                    if (intArr[num] == 0) {
                        if (num == this.size - 1) {        //所有权限已获取
                            mJoinPoint?.proceed()
                        }
                    }
                }
            }
        }
    }

    /**
     * 拦截当前的application
     */
    @After("execution(* android.app.Application.onCreate(..))")
    fun getCurrentApp(point: JoinPoint){
        (point.`this` as Application).registerActivityLifecycleCallbacks(mActivityLml)
    }

    /**
     * activity活动监听
     */
    private var mActivityLml=object: ActivityLifecycleIml {
        override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {
            super.onActivityCreated(activity, savedInstanceState)
            activity?.let {
                if(!mActivityList?.contains(activity)!!){
                    mActivityList?.add(activity)
                }
            }
        }

        override fun onActivityDestroyed(activity: Activity?) {
            super.onActivityDestroyed(activity)
            activity?.let {
                if(mActivityList?.contains(it)!!){
                    mActivityList?.remove(it)
                }
            }
        }
    }

    /**
     * 操作监听
     */
    private fun globleListener() {
        GlobalScope.launch {
            while (true) {
                val timeDelay=System.currentTimeMillis() - LAST_HANDLE_TIME
                Logger.debug("Global_0", "已执行时间：$timeDelay")
                if (LAST_HANDLE_TIME != 0L && (timeDelay> Constant.TIME_DIFFERENCE)){
                    Logger.debug("Global_1", "超过限定时间")
                    LAST_HANDLE_TIME = 0L
                    mActivityList?.let {
                        if(it.size!=0){
                            GlobalScope.launch (Dispatchers.Main){
                                ToastUtil.showShort(BaseApplication.context,"监听到程序长时间无操作，将自动退出")
                            }
                        }
                        while (it.iterator().hasNext()){
                            val iter=it.iterator()
                            val activity=iter.next()
                            activity.finish()
                            if(it.contains(activity)){
                                it.remove(activity)
                            }
                        }
                    }
                }else{
                    Logger.debug("Global","全局监控中")
                }
                delay(1000)
            }
        }
    }
}